package com.test.demo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.CalendarView;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.hcnetsdk.jna.HCNetSDKJNAInstance;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_PLAYBACK_INFO;
import com.hikvision.netsdk.NET_DVR_TIME;
import com.hikvision.netsdk.NET_DVR_VOD_PARA;
import com.hikvision.netsdk.PlaybackControlCommand;
import com.test.demo.R;
import com.test.demo.base.BaseActivity;
import com.test.demo.base.Constants;
import com.test.demo.utils.ScreenUtils;
import com.test.demo.utils.ToastUtil;
import com.test.demo.widget.RLPlaySurfaceView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 回放
 */
public class PlayBackActivity extends BaseActivity {

    @BindView(R.id.cv_datetime)
    CalendarView cvDatetime;
    @BindView(R.id.iv_pause)
    ImageView ivPause;

    private int m_iPlayID = -1; // return by NET_DVR_RealPlay_V40
    private int m_iPlaybackID = -1; // return by NET_DVR_PlayBackByTime
    private static final String TAG = "PlaybackActivity";
    private RLPlaySurfaceView rlPlaySurfaceView;
    private boolean m_bPlaybackByName = false;
    private int m_iStartChan;
    private int m_iLogID;
    private String title;
    private boolean isPause = false;//默认不暂停
    private int startYear;//开始年月日  默认显示一天的回放
    private int startMonth;
    private int startDay;
    private Handler handler = new Handler();

    @Override
    public int getContentView() {
        return R.layout.activity_play_back;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        m_iLogID = intent.getIntExtra(Constants.EXTRA.EXTRA_LOGID, -1);
        m_iStartChan = intent.getIntExtra(Constants.EXTRA.EXTRA_CHAN, -1);
        title = intent.getStringExtra(Constants.EXTRA.EXTRA_TITLE);
        Log.e(TAG, "init: m_iLogID=" + m_iLogID);
        Log.e(TAG, "init: m_iStartChan=" + m_iStartChan);
        rlPlaySurfaceView = new RLPlaySurfaceView(this);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        //计算位置
        int wid = metric.widthPixels - ScreenUtils.dip2px(this, 150);
        int calendarWidth = wid / 4;
        wid = (wid * 3) / 4;
        rlPlaySurfaceView.getPlaySurfaceView().setCallbackParam(wid * 2);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        params.leftMargin = calendarWidth + ScreenUtils.dip2px(this, 73);//40 padding margin
        params.topMargin = ScreenUtils.dip2px(this, 150);
        addContentView(rlPlaySurfaceView, params);
        Calendar calendar = Calendar.getInstance();
        this.startYear = calendar.get(Calendar.YEAR);
        this.startMonth = calendar.get(Calendar.MONTH) + 1;
        this.startDay = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCallbackPre(startYear, startMonth, startDay);
    }

    @Override
    protected void onPause() {
        super.onPause();
        HCNetSDK.getInstance().NET_DVR_StopPlayBack(m_iPlaybackID);
        rlPlaySurfaceView.setVisibility(View.GONE);
    }

    @OnClick({R.id.iv_back, R.id.iv_pause, R.id.iv_next, R.id.iv_2_full, R.id.iv_capture, R.id.iv_download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ToastUtil.TextToast(mContext, "慢放");
                startPlay(PlaybackControlCommand.NET_DVR_PLAYSLOW);//慢放
                break;
            case R.id.iv_pause:
                isPause = !isPause;
                ivPause.setImageResource(isPause ? R.mipmap.ic_control_stop : R.mipmap.ic_control_play);
                ToastUtil.TextToast(mContext, isPause ? "暂停" : "继续播放");
                startPlay(isPause ? PlaybackControlCommand.NET_DVR_PLAYPAUSE : PlaybackControlCommand.NET_DVR_PLAYRESTART);//播放暂停，恢复
                break;
            case R.id.iv_next:
                ToastUtil.TextToast(mContext, "快进");
                startPlay(PlaybackControlCommand.NET_DVR_PLAYFAST);//快放
                break;
            case R.id.iv_2_full:
                Intent intentFull = new Intent(mContext, FullScreenActivity.class);
                intentFull.putExtra(Constants.EXTRA.EXTRA_LOGID, m_iLogID);
                intentFull.putExtra(Constants.EXTRA.EXTRA_TITLE, title);
                intentFull.putExtra(Constants.EXTRA.EXTRA_CHAN, m_iStartChan);
                startActivity(intentFull);
                break;
            case R.id.iv_capture:
                capture();
                break;
            case R.id.iv_download:
                ToastUtil.TextToast(mContext, "下载");
                downloadVideo();
                break;
        }
    }

    private void startCallbackPre(int year, int month, int day) {
        //先停止播放回放 m_iPlaybackID
        if (m_iPlaybackID != -1) {
            HCNetSDK.getInstance().NET_DVR_StopPlayBack(m_iPlaybackID);
            m_iPlaybackID = -1;
            m_iPlayID = -1;
        }

        this.startYear = year;
        this.startMonth = month;
        this.startDay = day;

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startPlay(PlaybackControlCommand.NET_DVR_PLAYSTART);
            }
        }, 2000);
    }

    private void startPlay(int controlCode) {
        Log.e(TAG, "controlCode=" + controlCode);
        try {
            if (m_iLogID < 0) {
                return;
            }
            if (m_iPlaybackID < 0) {
                if (m_iPlayID >= 0) {
                    return;
                }

                if (!m_bPlaybackByName) {
                    NET_DVR_TIME timeStart = new NET_DVR_TIME();
                    NET_DVR_TIME timeStop = new NET_DVR_TIME();

                    timeStart.dwYear = startYear;
                    timeStart.dwMonth = startMonth;
                    timeStart.dwDay = startDay;
                    timeStart.dwHour = 0;
                    timeStart.dwMinute = 0;
                    timeStart.dwSecond = 0;

                    timeStop.dwYear = startYear;
                    timeStop.dwMonth = startMonth;
                    timeStop.dwDay = startDay;
                    timeStop.dwHour = 24;
                    timeStop.dwMinute = 0;
                    timeStop.dwSecond = 0;

                    NET_DVR_VOD_PARA vodParma = new NET_DVR_VOD_PARA();
                    vodParma.struBeginTime = timeStart;
                    vodParma.struEndTime = timeStop;
                    vodParma.byStreamType = 1;
                    vodParma.struIDInfo.dwChannel = m_iStartChan;
                    vodParma.hWnd = rlPlaySurfaceView.getPlaySurfaceView().getHolder().getSurface();
                    m_iPlaybackID = HCNetSDK.getInstance().NET_DVR_PlayBackByTime_V40(m_iLogID, vodParma);
                } else {
                    m_iPlaybackID = HCNetSDK.getInstance().NET_DVR_PlayBackByName(m_iLogID, new String("ch0001_00000000300000000"), rlPlaySurfaceView.getPlaySurfaceView().getHolder().getSurface());
                }
            }
            Log.e(TAG, "m_iPlaybackID=" + m_iPlaybackID);
            if (m_iPlaybackID >= 0) {
                NET_DVR_PLAYBACK_INFO struPlaybackInfo = null;
                if (!HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, controlCode, null, 0, null)) {
                    Log.e(TAG, "controlCode 回放操作失败");
                    return;
                }
                Log.e(TAG, "controlCode 回放操作成功");

//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYPAUSE, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PlayBackControl_V40 pause succ");
//                    }
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYRESTART, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYRESTART restart succ");
//                    }
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYFAST, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYFAST succ");
//                    }
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSLOW, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYSLOW succ");
//                    }
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSTARTAUDIO, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYSTARTAUDIO succ");
//                    }
//                    byte[] lpInBuf = new byte[60];
//                    lpInBuf[0] = 5;
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYAUDIOVOLUME, lpInBuf, 4, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYAUDIOVOLUME succ");
//                    } else {
//                        Log.e(TAG, "NET_DVR_PLAYAUDIOVOLUME fail");
//                    }
//                    if (HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(m_iPlaybackID, PlaybackControlCommand.NET_DVR_PLAYSTOPAUDIO, null, 0, struPlaybackInfo)) {
//                        Log.i(TAG, "NET_DVR_PLAYSTOPAUDIO succ");
//                    }

//                Thread thread11 = new Thread() {
//                    public void run() {
//                        int nProgress = -1;
//                        while (true) {
//                            nProgress = HCNetSDK.getInstance().NET_DVR_GetPlayBackPos(m_iPlaybackID);
//                            if (nProgress < 0 || nProgress >= 100) {
//                                break;
//                            }
//                            try {
//                                Thread.sleep(1000);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                };
//                thread11.start();
            } else {
                ToastUtil.TextToast(mContext, "获取该时间回放视频失败");
                m_iPlaybackID = -1;
                Log.e(TAG, "m_iPlaybackID<0回放相关操作失败");
            }
        } catch (Exception err) {
            Log.e(TAG, "error: " + err.toString());
            ToastUtil.TextToast(mContext, "获取该时间回放视频失败");
            m_iPlaybackID = -1;
        }
    }

    /**
     * 截图：动态请求 存储权限
     */
    private void capture() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh_mm_ss_Sss");
        String date = sDateFormat.format(new java.util.Date());
        File dir = new File(Environment.getExternalStorageDirectory() + "/capture");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, date + ".jpg");
        String absolutePath1 = file.getAbsolutePath();
        try {
            if (m_iPlayID < 0 && m_iPlaybackID < 0) {
                Log.e(TAG, "please start preview first");
                return;
            }
            if (m_iPlayID >= 0) {
                if (HCNetSDKJNAInstance.getInstance().NET_DVR_CapturePictureBlock(m_iPlayID, absolutePath1, 0)) {
                    ToastUtil.TextToast(mContext, "截图完成" + absolutePath1);
                } else {
                    ToastUtil.TextToast(mContext, "截图失败");
                    Log.e(TAG, "NET_DVR_CapturePictureBlock fail! Err:" + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            } else {
                if (HCNetSDKJNAInstance.getInstance().NET_DVR_PlayBackCaptureFile(m_iPlaybackID, absolutePath1)) {
                    ToastUtil.TextToast(mContext, "截图完成" + absolutePath1);
                } else {
                    ToastUtil.TextToast(mContext, "截图失败");
                    Log.e(TAG, "NET_DVR_PlayBackCaptureFile fail " + HCNetSDK.getInstance().NET_DVR_GetLastError());
                }
            }
        } catch (Exception err) {
            Log.e(TAG, "error: " + err.toString());
            ToastUtil.TextToast(mContext, "截图失败");
        }
    }

    private void downloadVideo() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh_mm_ss_Sss");
        String date = sDateFormat.format(new java.util.Date());
        File dir = new File(Environment.getExternalStorageDirectory() + "/download");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, date + "");
        if (m_iLogID < 0 || m_iStartChan < 0) {
            ToastUtil.TextToast(mContext, "下载失败");
            return;
        }
        NET_DVR_TIME timeStart = new NET_DVR_TIME();
        NET_DVR_TIME timeStop = new NET_DVR_TIME();

        timeStart.dwYear = startYear;
        timeStart.dwMonth = startMonth;
        timeStart.dwDay = startDay;
        timeStart.dwHour = 0;
        timeStart.dwMinute = 0;
        timeStart.dwSecond = 0;

        timeStop.dwYear = startYear;
        timeStop.dwMonth = startMonth;
        timeStop.dwDay = startDay;
        timeStop.dwHour = 0;
        timeStop.dwMinute = 0;
        timeStop.dwSecond = 0;
        int getFileByTimeRet = HCNetSDK.getInstance().NET_DVR_GetFileByTime(m_iLogID, m_iStartChan, timeStart, timeStop, file.getAbsolutePath());
        if (getFileByTimeRet == -1) {
            ToastUtil.TextToast(mContext, "下载失败");
            return;
        }
        boolean downloadRet = HCNetSDK.getInstance().NET_DVR_PlayBackControl_V40(getFileByTimeRet,
                PlaybackControlCommand.NET_DVR_PLAYSTART, null, 0, null);
        ToastUtil.TextToast(mContext, downloadRet ? "下载中" : "下载失败");

        if (downloadRet) {
            Thread thread11 = new Thread() {
                public void run() {
                    int nProgress = -1;
                    while (true) {
                        nProgress = HCNetSDK.getInstance().NET_DVR_GetDownloadPos(m_iPlaybackID);
                        if (nProgress < 0) {
                            ToastUtil.TextToast(mContext, "下载结束");
                            break;
                        }
                        if (nProgress >= 100) {
                            ToastUtil.TextToast(mContext, "下载完成");
                            break;
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            thread11.start();
        }
    }

    public void onBack(View view) {
        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("m_iPlayID", m_iPlayID);
        outState.putInt("m_iStartChan", m_iStartChan);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        m_iPlayID = savedInstanceState.getInt("m_iPlayID");
        m_iStartChan = savedInstanceState.getInt("m_iStartChan");
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HCNetSDK.getInstance().NET_DVR_StopPlayBack(m_iPlaybackID);
        m_iPlaybackID = -1;
    }
}
